package com.changyou.kf.core.listener;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;

import java.lang.management.ManagementFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class StartedEventListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {

        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        String appName = System.getProperty("APP_NAME");
        String pid = System.getProperty("PID");
        String hostname = System.getProperty("HOSTNAME");
        String port = environment.getProperty("server.port");
        String javaVersion = System.getProperty("java.version");
        String userName = System.getProperty("user.name");
        String userDir = System.getProperty("user.dir");


        StringBuffer buffer = new StringBuffer();
        buffer.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")))
                .append(" [INFO ] [main] Started using Java ").append(javaVersion)
                .append(" on ").append(hostname).append(":").append(port)
                .append(" with PID ").append(pid)
                .append(" by ").append(userName)
                .append(" in ").append(userDir);
        try {
            double uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0;
            buffer.append(" (JVM running for ").append(uptime).append(")");
        } catch (Throwable ex) {
            // No JVM time available
        }
        System.out.println(buffer.toString());
        // Started K8sApplication in 13.965 seconds (JVM running for 17.081)
        //System.out.println("==================StartedEventListener==================");
    }

}
